﻿#pragma once

#include <QWidget>
#include "ui_MyTcpServerWidget.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#include <QStandardItemModel>
#include <QSortFilterProxyModel>
#include <QTableWidgetItem>

struct Payload_tableWidget_ItemData
{
	QString time;
	QString source;
	QString from;
	QString payload;
	QString data;
	QString result;
};

struct Client_tableWidget_ItemData
{
	QString time;
	QString uuid;
	QString imei;
};

struct TcpClientData
{
	QByteArray data;
	QTimer *timer;
	QString uuid;
	QString imei;
};

struct UserPayload_tableWidget_ItemData
{
	QString description;
	QString data;

	UserPayload_tableWidget_ItemData(const QString &desc, const QString &d)
		: description(desc), data(d)
	{
	}
};

class MyTcpServerWidget : public QWidget
{
	Q_OBJECT

public:
	MyTcpServerWidget(QWidget *parent = nullptr);
	~MyTcpServerWidget();

private slots:
	void on_tcp_client_connected();
	void on_tcp_client_disconnected();
	void on_tcp_client_ready_read();

	void on_start_listen_btn_clicked();
	void on_clear_btn_clicked();
	void on_export_csv_btn_clicked();

	void on_filter_edit_text_changed(const QString &text);

	void set_send_msg_btn_enable();

	void on_send_msg_btn_clicked();

	void on_user_payload_tableWidget_item_changed(QTableWidgetItem *item);

	void on_add_user_payload_btn_clicked();

	void on_delete_user_payload_btn_clicked();

	void on_select_user_payload_btn_clicked();

	void on_send_user_payload_btn_clicked();

	void save_user_payload();

	void on_tips_timer_timeout();

private:
	void insert_to_payload_tableWidget(const Payload_tableWidget_ItemData &data);
	void insert_to_client_tableWidget(const Client_tableWidget_ItemData &data);

	int encode_payload(const QString imei, const QByteArray &data, QByteArray &payload);

	QString decode_payload(const QByteArray &data);

	void add_send_msg_item(const UserPayload_tableWidget_ItemData &data);

	void load_user_payload();

	void show_tips(const QString &tips);

	void send_message(const QString &data);

private:
	Ui::MyTcpServerWidgetClass ui;

	// payload tableView model
	QStandardItemModel *m_payload_model;
	// proxy model
	QSortFilterProxyModel *m_payload_proxy_model;

	QMap<QTcpSocket *, struct TcpClientData> m_client_data;

	QTimer *hide_tips_timer;

	QTcpServer *m_server;
};
